<template>
   <div class="chooser-component">    <!--多选组件 -->
    <ul class="chooser-list">
      <li
        v-for="(item,index) in selections"
        @click="toggleSelection(index)"
        :title="item.label"
        :class="{active: checkActive(index)}"
      >{{item.label}}</li>
    </ul>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  props:{
    selections:{
      type:Array,
      default:[{
         label: 'test',
         value: 0
      }]
    }
  },
  data() {
    return {
      nowIndexes:[0]
    }
  },
  methods: {
    toggleSelection (index) {
      if (this.nowIndexes.indexOf(index) === -1) {
        this.nowIndexes.push(index)  //没有的话添加
      }
      else {
        this.nowIndexes = _.remove(this.nowIndexes, (idx) => { //有的话就剔除掉，返回数组
          return idx !== index
        })
      }
      let nowObjArray = _.map(this.nowIndexes, (idx) => {   //改变成对象的形式
        return this.selections[idx]
      })
      this.$emit('on-change', nowObjArray)   //把数据对象传递出去
    },
    checkActive (index) {
      return this.nowIndexes.indexOf(index) !== -1  //是否属于该数组里，在的话返回true添加样式
    }
  }

}
</script>

<style scoped>
.chooser-component {
  position: relative;
  display: inline-block;
}
.chooser-list li{
  display: inline-block;
  border: 1px solid #e3e3e3;
  height: 25px;
  line-height: 25px;
  padding: 0 8px;
  margin-right: 5px;
  border-radius: 3px;
  text-align: center;
  cursor: pointer;
}
.chooser-list li.active {
  border-color: #4fc08d;
  background: #4fc08d;
  color: #fff;
}
</style>
